package com.yizn.learn.concurrent;

import apple.laf.JRSUIConstants;

import java.util.concurrent.Semaphore;

/**
 * 信号量列子
 *
 * @author yisl
 * @create 2020-08-30 14:47
 */
public class SemaphoreTest {

    static  class Parking{
        private  Semaphore semaphore;

        Parking(int count){
            semaphore = new Semaphore(count);
        }

        private void  parking(){

            try {
                semaphore.acquire();
                long time = (long) (Math.random() * 10);
                System.out.println(Thread.currentThread().getName() + "进入停车场，开始停车" + time + "秒");
                Thread.sleep(time);
                semaphore.release();
                System.out.println(Thread.currentThread().getName() + "离开停车场");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Car extends Thread{
        private Parking parking;
        Car(Parking parking){
            this.parking = parking;
        }

        @Override
        public void run() {
            parking.parking();
        }
    }

    public static void main(String[] args) {
        Parking parking = new Parking(2);
        for(int i=0; i<5; i++){
            new Car(parking).start();
        }

    }
}
